package com.tbvtc.agriculturalcreditchainserver2025.config;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.Item;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Cart.CartSelectUserByUserIdVo;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class JsonToListTypeHandler1  extends BaseTypeHandler<List<CartSelectUserByUserIdVo>> {
    private static final ObjectMapper objectMapper = new ObjectMapper();



    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<CartSelectUserByUserIdVo> parameter, JdbcType jdbcType) throws SQLException {

    }

    @Override
    public List<CartSelectUserByUserIdVo> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJson(rs.getString(columnName));
    }

    @Override
    public List<CartSelectUserByUserIdVo> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJson(rs.getString(columnIndex));
    }

    @Override
    public List<CartSelectUserByUserIdVo> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJson(cs.getString(columnIndex));
    }

    private List<CartSelectUserByUserIdVo> parseJson(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<List<CartSelectUserByUserIdVo>>() {});
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }
}
